﻿/*
 * Copyright (c) 2015-2016 Constantijn Evenhuis (blueprints@const.nl)
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
using Blueprints.Defaults;
using Blueprints.Resolution;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace Blueprints
{
    /// <summary>
    /// The default type resolver.
    /// </summary>
    public partial class DefaultTypeResolver : ITypeResolver
    {
        private readonly IDictionary<Type, IValueDescriptor> valueDescriptors;

        /// <summary>
        /// Creates a new default type resolver.
        /// </summary>
        public DefaultTypeResolver()
            : this(typeof(object))
        {
        }

        /// <summary>
        /// Creates a new default type resolver.
        /// </summary>
        public DefaultTypeResolver(IncludeProperties includeProperties)
            : this(typeof(object), includeProperties)
        {
        }

        /// <summary>
        /// Creates a new default type resolver.
        /// </summary>
        /// <param name="targetType">The target type of the context in which this resolver will participate.</param>
        public DefaultTypeResolver(Type targetType)
            : this(targetType, IncludeProperties.IncludePublicGetSetProperties | IncludeProperties.GuessStructConstructorByProperties)
        {
        }


        /// <summary>
        /// Creates a new default type resolver.
        /// </summary>
        /// <param name="targetType">The target type of the context in which this resolver will participate.</param>
        /// <param name="includeProperties">The properties that should be included in serialization.</param>
        public DefaultTypeResolver(Type targetType, IncludeProperties includeProperties)
        {
            TargetType = targetType;
            IncludeProperties = includeProperties;
            valueDescriptors = new Dictionary<Type, IValueDescriptor>();
            foreach (KeyValuePair<Type, IValueDescriptor> descriptor in GetValueDescriptors())
            {
                valueDescriptors.Add(descriptor);
            }
        }

        /// <summary>
        /// Gets the target type of the context in which this resolver participates.
        /// </summary>
        public Type TargetType
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the properties that are to be included in serialization.
        /// </summary>
        public IncludeProperties IncludeProperties
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the type category for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to inspect.</param>
        /// <returns>The type category for <paramref name="type"/>.</returns>
        public virtual TypeCategory GetTypeCategory(Type type)
        {
            TypeInfo typeInfo = type.GetTypeInfo();
            if (valueDescriptors.ContainsKey(type) || typeInfo.IsEnum)
            {
                return TypeCategory.Value;
            }

            if (type.IsArray)
            {
                return TypeCategory.Array;
            }

            if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(typeInfo))
            {
                MethodInfo addMethod;
                Type elementType;
                if (DefaultCollectionDescriptor.TryGetAddMethod(type, out addMethod, out elementType))
                {
                    return TypeCategory.Collection;
                }
            }

            if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(PropertyBucket<>))
            {
                return TypeCategory.Object;
            }

            if (DefaultObjectDescriptor.CanCreateObjectDescriptor(type, TargetType, IncludeProperties))
            {
                return TypeCategory.Object;
            }

            return TypeCategory.NotInstantiable;
        }

        /// <summary>
        /// Gets the value descriptor for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to get the descriptor for.</param>
        /// <returns>The value descriptor for <paramref name="type"/>.</returns>
        public virtual IValueDescriptor GetValueDescriptor(Type type)
        {
            IValueDescriptor descriptor;
            if (valueDescriptors.TryGetValue(type, out descriptor))
            {
                return descriptor;
            }

            TypeInfo typeInfo = type.GetTypeInfo();
            ValueDescriptorAttribute attr = typeInfo.GetCustomAttribute<ValueDescriptorAttribute>();
            if (attr != null)
            {
                descriptor = attr.CreateResolver<IValueDescriptor>(TargetType);
                valueDescriptors[type] = descriptor;
                return descriptor;
            }

            if (typeInfo.IsEnum)
            {
                descriptor = new EnumValueDescriptor(type);
                valueDescriptors[type] = descriptor;
                return descriptor;
            }

            throw new BlueprintException("No value descriptor found for type '" + type.Name + "'");
        }

        /// <summary>
        /// Gets the object descriptor for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to get the descriptor for.</param>
        /// <returns>The object descriptor for <paramref name="type"/>.</returns>
        public virtual IObjectDescriptor GetObjectDescriptor(Type type)
        {
            if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(PropertyBucket<>))
            {
                return new PropertyBucketObjectDescriptor(type, this);
            }

            if (type.IsConstructedGenericType)
            {
                Type typeDefinition = type.GetGenericTypeDefinition();
                if (typeDefinition == typeof(KeyValuePair<,>))
                {
                    return new DefaultKeyValuePairDescriptor(type);
                }
            }

            return new DefaultObjectDescriptor(this, type, IncludeProperties);
        }

        /// <summary>
        /// Gets the array descriptor for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to get the descriptor for.</param>
        /// <returns>The array descriptor for <paramref name="type"/>.</returns>
        public virtual IArrayDescriptor GetArrayDescriptor(Type type)
        {
            return new DefaultArrayDescriptor(type);
        }

        /// <summary>
        /// Gets the collection descriptor for <paramref name="type"/>.
        /// </summary>
        /// <param name="type">The type to get the descriptor for.</param>
        /// <returns>The collection descriptor for <paramref name="type"/>.</returns>
        public virtual ICollectionDescriptor GetCollectionDescriptor(Type type)
        {
            return new DefaultCollectionDescriptor(type);
        }

        /// <summary>
        /// Attempts to resolve a type.
        /// </summary>
        /// <param name="name">The name of the type.</param>
        /// <param name="type">The resolved type.</param>
        /// <returns>True if the type was successfully resolved, false otherwise.</returns>
        public virtual bool TryGetType(string name, out Type type)
        {
            try
            {
                type = Type.GetType(name, false);
                return type != null;
            }
            catch
            {
                type = default(Type);
                return false;
            }
        }

        /// <summary>
        /// Gets the name of the type.
        /// </summary>
        /// <param name="type">The type to get the name of.</param>
        /// <returns>The name of the type.</returns>
        public virtual string GetTypeName(Type type)
        {
            AssemblyName assemblyName = new AssemblyName(type.GetTypeInfo().Assembly.FullName);
            if (assemblyName.GetPublicKeyToken().Length == 0)
            {
                return type.FullName + ", " + assemblyName.Name;
            }

            return type.AssemblyQualifiedName;
        }
    }
}